"""
Case Type   : 故障&可靠性测试
Case Name   : xml文件权限异常，备机扩容成功
Create At   : 2022/4/8
Owner       : n@ningyali
Description :
    1、更改执行备机扩容命令所在主机的xml文件权限，chmod 000 ***.xml
    2、备机扩容
Expect      :
    1、更改文件权限成功
    2、扩容成功
History     :
"""
import os
import re
import time
import unittest
from datetime import datetime

from yat.test import macro

from testcase.utils.ComThread import ComThread
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH, RestartDbCluster
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class GsExpansion19(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.sh = {'pri_root': CommonSH('PrimaryRoot'),
                   'pri_user': CommonSH(self.nodes_tuple[0]),
                   'sta1_user': CommonSH(self.nodes_tuple[1]),
                   'sta2_user': CommonSH(self.nodes_tuple[2])}
        self.node_num = self.sh['pri_user'].get_node_num()
        self.log = Logger()
        self.cons = Constant()
        self.com = Common()
        text = f'-----{os.path.basename(__file__)} start-----'
        self.log.info(text)

        text = '----预置步骤: 一主两备减容一备，后续用例才能扩容 expect: 成功----'
        self.log.info(text)
        expect_msg = 'Success to drop the target nodes'
        shell_cmd = f'''source {macro.DB_ENV_PATH};
                    expect <<EOF
                    set timeout 300
                    spawn gs_dropnode -U {self.sh['pri_user'].node.ssh_user} \
                    -G {self.sh['pri_user'].node.ssh_user} \
                    -h {self.sh.get("sta1_user").node.ssh_host}
                    expect "*(yes/no)?"
                    send "yes\\n"
                    expect eof''' + "\nEOF\n"
        self.log.info(shell_cmd)
        res = self.com.get_sh_result(self.sh['pri_user'].node, shell_cmd)
        self.assertIn(expect_msg, res, f'执行失败: {text}')

        text = '---预置步骤: 数据库主机解压安装包，以免找不到扩容脚本 expect: 成功---'
        self.log.info(text)
        cmd = f'cd {os.path.dirname(macro.DB_SCRIPT_PATH)} && ' \
            f'tar -xf openGauss-Package-bak*.tar.gz && ' \
            f'ls {macro.DB_SCRIPT_PATH}|grep gs_sshexkey'
        self.log.info(cmd)
        res = self.com.get_sh_result(self.sh.get("pri_root").node, cmd)
        self.assertEqual(res, 'gs_sshexkey', f'执行失败: {text}')

        text = '----获取xml文件权限，teardown用来还原 expect: 成功----'
        self.log.info(text)
        cmd = f'stat -c %a {macro.DB_XML_PATH}'
        self.log.info(cmd)
        self.xml_perm = self.com.get_sh_result(self.sh.get("pri_root").node,
                                               cmd).strip()
        self.assertEqual(len(self.xml_perm), 3, f'执行失败: {text}')

    def test_1(self):
        text = '----step1: 更改执行备机扩容命令所在主机的xml文件权限 expect: 更改文件权限成功----'
        self.log.info(text)
        cmd = f'chmod 000 {macro.DB_XML_PATH}'
        self.log.info(cmd)
        res = self.com.get_sh_result(self.sh.get("pri_root").node, cmd)
        self.assertEqual(len(res), 0, f'执行失败: {text}')

        text = '----step2: 备机扩容 expect: 扩容成功----'
        self.log.info(text)
        text = '----step2.1: 建立root互信 expect: 成功----'
        self.log.info(text)
        ssh_cmd = f'cd {macro.DB_SCRIPT_PATH};' \
            f'echo "{self.sh.get("pri_root").node.ssh_host}\n' \
            f'{self.sh.get("sta1_user").node.ssh_host}\n' \
            f'{self.sh.get("sta2_user").node.ssh_host}" > hosts\n'
        ssh_cmd += f'''expect <<EOF
                    set timeout 300
                    spawn ./gs_sshexkey -f hosts
                    expect "*assword:"
                    send "{self.sh.get("pri_root").node.ssh_password}\\n"
                    expect eof''' + "\nEOF\n"
        ssh_cmd += "source ~/.bashrc"
        self.log.info(ssh_cmd)
        res = self.com.get_sh_result(self.sh.get("pri_root").node, ssh_cmd)
        self.assertIn('Successfully created SSH trust', res, f'执行失败: {text}')

        text = '----step2.2: 执行备机扩容 expect: 执行成功----'
        self.log.info(text)
        expansion_cmd = f'cd {macro.DB_SCRIPT_PATH};' \
            f'source {macro.DB_ENV_PATH}\n' \
            f'./gs_expansion -U {self.sh.get("pri_user").node.ssh_user} ' \
            f'-G {self.sh.get("pri_user").node.ssh_user} ' \
            f'-X {macro.DB_XML_PATH} ' \
            f'-h {self.sh.get("sta1_user").node.ssh_host} -L'
        self.log.info(expansion_cmd)
        res = self.com.get_sh_result(self.sh.get("pri_root").node,
                                     expansion_cmd)
        expect = 'Expansion results:.*:.*Success.*Expansion Finish.'
        regex_res = re.search(expect, res, re.S)
        self.assertIsNotNone(regex_res, f'执行失败: {text}')

    def tearDown(self):
        text = '----run teardown----'
        self.log.info(text)

        text1 = '----还原xml权限 expect: 成功----'
        self.log.info(text1)
        cmd = f'chmod {self.xml_perm} {macro.DB_XML_PATH}'
        self.log.info(cmd)
        res1 = self.com.get_sh_result(self.sh.get("pri_root").node, cmd)

        text = '----检查集群状态是否正常----'
        self.log.info(text)
        res2 = self.sh['pri_user'].getDbClusterStatus('detail')
        self.log.info(res2)

        self.assertEqual(len(res1), 0, f'执行失败: {text1}')
        self.assertEqual(res2.count('Normal'), self.node_num + 1,
                         f'执行失败: {text}')

        text = f'-----{os.path.basename(__file__)} end-----'
        self.log.info(text)
